<?php

//$config = require_once('../config/config.php');
$root =  dirname(dirname(dirname(__FILE__)));
$config = require_once($root . '/src/config/config.php');

function writeToCache($file, $data) {
    if(!file_put_contents($file, $data)) {
        exit('Can not write to cache files.');
    }
}


$conn = mysql_connect($config['db_config']['host'], $config['db_config']['user'], $config['db_config']['pass']) or die("connect failed" . mysql_error());
mysql_set_charset($config['db_config']['charset'],$conn);
mysql_select_db($config['db_config']['database'], $conn);

$var = '上海';
$sql = 'select phone_number,location from '.$config['db_config']['tablename'].' where location like "'.$var.'%" order by phone_number limit 1';

$result = mysql_query($sql, $conn);
$ret = '';
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
//    var_dump($row['location']);
    $ret = str_replace('上海', '', $row['location']);
//    var_dump($ret);
//    $row['location'] = str_replace($ret, '  ', $row['location']);
//    var_dump($row['location']);
}

$suffix = array(130,131,132,145,155,156,185,186,134,135,136,137,138,139,150,151,152,157,158,159,147,182,183,184,187,188,133,153,180,181,189);
$multiple = $config['mobile']['segment'];

@mkdir($root . "/data");
@mkdir($root . "/data/mobile");
$dir = $root . "/data/mobile/";
$distinct = array();
$target = $i = 0;
$tmp_data = "";

foreach($suffix as $var) {

//    $dir = "../../data/mobile/".$var;
//    if (!mkdir($dir)) {
//        exit("Failed to create folders...");
//    }

    $sql = "select phone_number,location from ".$config['db_config']['tablename']." where phone_number like \"".$var."%\" order by phone_number;";
//    var_dump($sql);
//    exit();
    $result = mysql_query($sql, $conn);
//    $rows = array();

//    $cnt = 0;

    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

        $row['location'] = trim(str_replace($ret, ' ', $row['location']));
//        array_search('green', $array);
        $res = array_search($row['location'], $distinct);
        if ($res === false) {
            $distinct[$i] = $row['location'];
//            array_push($distinct, ($row['location']));
            $target = $i;
            $i ++;
        } else {
            $target = $res;
        }
//        if ($i < SEGEMENT) {
            $tmp_data .= str_pad(pack('S', $target), 2);
//        } else {
//            writeToCache($dir."/".($cnt*$config), $tmp_data);
//            $cnt ++;
//            $i = 0;
//            $tmp_data = str_pad(trim($row['location']), 60);
//        }
//        $i ++;
    }
//    writeToCache($dir."/".($cnt*$config['mobile']['segment']), $tmp_data);
}

$data = '<?php'."\n".' return '. var_export($distinct, TRUE). "; \n";

writeToCache($dir."/index.php", $data);
writeToCache($dir."/data", $tmp_data);
echo "done";
